// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using log4net;
using NHibernate.Validator.Engine;
using YoProgramo.Domain.BusinessLogic.Attributes;
using YoProgramo.Domain.BusinessLogic.Extensions;
using YoProgramo.Domain.BusinessLogic.Service;
using YoProgramo.Domain.Core;
using YoProgramo.Domain.Core.Exceptions;
using YoProgramo.Domain.Core.Interfaces;
using YoProgramo.Infrastructure.Tools.PagedList;

namespace YoProgramo.Web.Controllers
{
    public class UserController : Controller
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(StoryController));

        private IUserRepository _userrepository;
        private IUserService _userservice;
        private IStoryService _storyservice;
        public UserController(IUserRepository userrepository, IUserService userservice, IStoryService storyservice)
        {
            _userrepository = userrepository;
            _userservice = userservice;
            _storyservice = storyservice;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ViewProfile(int id) {            
            IUser user = _userrepository.Get(id);            
            return View(user);
        }

        public ActionResult Details(int id)
        {
            return View();
        }


        public ActionResult List(int? page) {
            ViewData["UrlPaging"] = Url.RouteUrl("AllUsersPaggin", new { controller = "User", action = "List", page = "__PAGENUM__"}); 
            IList<IUser> users = _userservice.GetAllNotSpammer().ToPagedList(page ?? 0, 24);
            return View(users);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        [YpAuthorize(Roles = new Roles[] { Roles.User, Roles.Administrator })]
        public ActionResult StoryList(int id, int? page) {
            ViewData["UrlPaging"] = Url.RouteUrl("ViewUserItemsPaging", new { controller = "User", action = "StoryList", page = "__PAGENUM__", id= id});
            IUser user = _userrepository.Get(id);
            IUser userLogged = _userservice.GetByUserName(HttpContext.User.Identity.Name);
            if (user.Id == userLogged.Id || userLogged.IsInRole(Roles.Administrator)) {
                return View(_storyservice.GetByUser(user).ToPagedList(page ?? 0, 10));
            }
            return RedirectToRoute("Default", new { action = "Index", controller = "Home" });            
        }


        [AcceptVerbs(HttpVerbs.Get)]
        [YpAuthorize(Roles = new Roles[] { Roles.User, Roles.Administrator })]
        public ActionResult FavoriteList(int id, int? page) {
            ViewData["UrlPaging"] = Url.RouteUrl("ViewUserFavoriteItemsPaging", new { controller = "User", action = "FavoriteList", page = "__PAGENUM__", id = id });
            IUser user = _userrepository.Get(id);
            IUser userLogged = _userservice.GetByUserName(HttpContext.User.Identity.Name);
            if (user.Id == userLogged.Id || userLogged.IsInRole(Roles.Administrator))
            {
                return View(user.FavoritesStories.ToPagedList(page ?? 0, 10));
            }
            return RedirectToRoute("Default", new { action = "Index", controller = "Home" });
        } 

        public ActionResult Create()
        {
            return View();
        } 

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [HandleError]
        [AcceptVerbs(HttpVerbs.Get)]
        [YpAuthorize(Roles = new Roles[] { Roles.User, Roles.Administrator })]        
        public ActionResult Edit(int id)
        {
            IUser userLogged = _userservice.GetByUserName(HttpContext.User.Identity.Name);
            IUser user = _userrepository.Get(id);
            if (user.Id == userLogged.Id || userLogged.IsInRole(Roles.Administrator))
            {
                return View(user);
            }
            return RedirectToRoute("Default", new { action = "Index", controller = "Home" });            
        }

        [HandleError]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        [YpAuthorize(Roles = new Roles[] { Roles.User, Roles.Administrator })]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                IUser userLogged = _userservice.GetByUserName(HttpContext.User.Identity.Name);

                IUser user = _userrepository.Get(id);
                user.Age = Int32.Parse(collection["user.Age"]);
                user.Pais = collection["user.Pais"];
                user.Bio = collection["user.Bio"];
                user.Site = collection["user.Site"];

                if (user.Id == userLogged.Id || userLogged.IsInRole(Roles.Administrator)) {
                    InvalidValue[] createStatus =  _userservice.Update(user);

                    if (createStatus.Count() > 0)
                    {
                        foreach (InvalidValue error in createStatus) {
                            ModelState.AddModelError(error.PropertyName, error.Message);
                        }
                    }
                    else
                    {
                        return RedirectToRoute("Default", new { controller = "User", action = "ViewProfile", id = user.Id });
                    }
                }

                return View(user);
            }
            catch( Exception ex)
            {
                throw new YPException("Error in edit user Action: " + ex.Message) ;
            }
        }
    }
}
